package liuliu.throughwaring.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import net.tsz.afinal.FinalDb;

import java.util.ArrayList;
import java.util.List;

import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.NoticeModel;

/**
 * Created by Administrator on 2016/3/24.
 */
public class UpdateMain extends Service {
    public FinalDb db;
    private Handler handler = new Handler();
    List<NoticeModel> noticeModelList = new ArrayList<NoticeModel>();
    List<CompanyModel> companyModelList = new ArrayList<CompanyModel>();

    @Override
    public void onCreate() {
        super.onCreate();
        db = FinalDb.create(this);

    }

    public class UpdateMainBind extends Binder {

        public IBinder Refush(final GetNoticeFace face) {
            new Thread(runnable).start();
            handler = new Handler() {
                public void handleMessage(Message msg) {
                    noticeModelList = db.findAllByWhere(NoticeModel.class, "IsRead='0'");
                    companyModelList=db.findAll(CompanyModel.class);
                    companyModelList = db.findAllByWhere(CompanyModel.class, "IsPush='true' and CompanyType='Company' order by CompanyCreateTime");
                    face.FaceShow(companyModelList.size(), noticeModelList.size());
                }
            };
            return null;
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Message msg = handler.obtainMessage();
            msg.obj = 0;
            handler.sendMessage(msg);
            handler.postDelayed(this, 5000);
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return new UpdateMainBind();
    }

    public interface GetNoticeFace {
        void FaceShow(int companyCount, int noticeCount);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        onDestroy();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }
}
